import { DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons';
import type { ArtColumn } from 'ali-react-table';
import { Form, InputNumber, Radio, Select, Space } from 'antd';
import TimeSlotInput from '../TimeSlotInput';
import _ from 'lodash';
// @ts-ignore
import { TIME_96 } from '@/pages/ETrade/components/helper';

type ColumnsOptionsType = {
  dataSourceList: any[];
  changeUseType: (value: any, index: number) => void;
  changeDataList: (index: number, type: 'delete' | 'add') => void;
  onBlurCapture?: (e: any) => void;
};

const getColumns = ({
  dataSourceList,
  changeUseType,
  changeDataList,
  onBlurCapture,
}: ColumnsOptionsType): ArtColumn[] => {
  return [
    {
      name: '时间段',
      width: 110,
      align: 'center',
      code: 'index',
      render: (_, row, index) => {
        return (
          <div className="edit-fixd first-td">
            <Form.Item name={`beginTime@${row.id}`}>
              <TimeSlotInput
                inputProps={{
                  onBlurCapture,
                }}
              />
            </Form.Item>
            <div className="divider"> — </div>
            <Form.Item name={`endTime@${row.id}`}>
              <TimeSlotInput
                inputProps={{
                  onBlurCapture,
                }}
              />
            </Form.Item>
          </div>
        );
      },
    },
    {
      name: '调整比例(%)',
      width: 80,
      align: 'center',
      code: 'rateValue',
      render: (_, row, index) => {
        return (
          <div className="edit-fixd">
            <Form.Item name={`useType@${row.id}`}>
              <Radio.Group onChange={(value) => changeUseType(value, index)}>
                <Radio value="dataSource" />
              </Radio.Group>
            </Form.Item>
            <Form.Item name={`rateValue@${row.id}`}>
              <InputNumber size="small" disabled={row.useType !== 'dataSource'} />
            </Form.Item>
          </div>
        );
      },
    },
    {
      name: '基准预测源',
      width: 80,
      align: 'center',
      code: 'dataSourceId',
      render: (_, row, index) => {
        return (
          <Form.Item name={`dataSourceId@${row.id}`}>
            <Select size="small" disabled={row.useType !== 'dataSource'}>
              {dataSourceList?.map((v) => (
                <Select.Option key={v.dataSourceId} value={v.dataSourceId}>
                  {v.dataSourceName}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        );
      },
    },
    {
      name: '最大值',
      width: 70,
      align: 'center',
      code: 'maxValue',
      render: (_, row, index) => {
        return (
          <Form.Item name={`maxValue@${row.id}`}>
            <InputNumber size="small" precision={3} disabled={row.useType !== 'dataSource'} />
          </Form.Item>
        );
      },
    },
    {
      name: '最小值',
      width: 70,
      align: 'center',
      code: 'minValue',
      render: (_, row, index) => {
        return (
          <Form.Item name={`minValue@${row.id}`}>
            <InputNumber size="small" precision={3} disabled={row.useType !== 'dataSource'} />
          </Form.Item>
        );
      },
    },
    {
      name: '固定值',
      width: 80,
      align: 'center',
      code: 'fixedValue',
      render: (_, row, index) => {
        return (
          <div className="edit-fixd">
            <Form.Item name={`useType@${row.id}`}>
              <Radio.Group onChange={(value) => changeUseType(value, index)}>
                <Radio value="fixation" />
              </Radio.Group>
            </Form.Item>
            <Form.Item name={`fixedValue@${row.id}`}>
              <InputNumber size="small" disabled={row.useType !== 'fixation'} />
            </Form.Item>
          </div>
        );
      },
    },
    {
      name: '操作',
      width: 60,
      align: 'center',
      code: 'options',
      render: (_, row, index) => {
        return (
          <Space size={'small'}>
            <DeleteOutlined
              style={{ color: '#eb5757' }}
              onClick={() => changeDataList(index, 'delete')}
            />
            <PlusCircleOutlined
              style={{ color: 'var(--bd-primary)' }}
              onClick={() => changeDataList(index, 'add')}
            />
          </Space>
        );
      },
    },
  ];
};

// 防止时点穿插,合并时段
const buildContinuousTimePoint = (arr: any = []) => {
  if (arr.length > 1) {
    let list = _.cloneDeep(arr);

    // 处理beginTime大于endTime的情况（自动交换）
    list = list.map((range: any) => {
      let { beginIndex, endIndex } = range; // 解构出其他字段
      if (beginIndex > endIndex) {
        [beginIndex, endIndex] = [endIndex, beginIndex];
      }
      return { ...range, beginIndex, endIndex }; // 保留所有字段
    });

    let timePointArr: any = [];

    // 去重完全重合的时段
    list.forEach((i: any) => {
      if (
        !timePointArr.some(
          (s: any) => `${s.beginIndex}-${s.endIndex}` === `${i.beginIndex}-${i.endIndex}`,
        )
      ) {
        timePointArr.push([i.beginIndex, i.endIndex]);
      }
    });
    // 平铺二维排序
    timePointArr = timePointArr.flat(1);

    // 从小到大排序
    timePointArr.sort((a: any, b: any) => a - b);

    // 生成二维数组
    const doubleArr = [];
    for (let i = 0; i < timePointArr.length; i += 2) {
      const pair = timePointArr.slice(i, i + 2);
      doubleArr.push(pair);
    }

    // 自动补全
    const result: any = [doubleArr[0]];
    for (let i = 1; i < doubleArr.length; i += 1) {
      const beginIndex = doubleArr[i][0];
      const endIndex = doubleArr[i][1];
      const lastEndIndex = doubleArr[i - 1]?.[1];
      if (beginIndex <= lastEndIndex) {
        result.push([lastEndIndex + 1, endIndex]);
      } else {
        result.push(doubleArr[i]);
      }
    }

    return result.map((arr: any, index: number) => {
      const data = list?.[index] ? list?.[index] : list[0];
      const beginIndex = arr[0];
      const endIndex = arr[1];
      return {
        ...data,
        id: _.uniqueId('new'),
        beginIndex,
        endIndex,
        beginTime: TIME_96[beginIndex],
        endTime: TIME_96[endIndex],
      };
    });
  } else {
    return arr;
  }
};

export { getColumns, buildContinuousTimePoint };
